/**
 * 
 */
package com.wubo.bm.common.service.impl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wubo.bm.common.entity.Response;
import com.wubo.bm.common.service.IResponseService;
import com.wubo.bm.exception.BackendException;
import com.wubo.spring.hibernate.BaseHibernateDao;
import com.wubo.spring.hibernate.EntityService;

/**
 * @author WuBo
 * @CreateDate 2012-2-24 上午09:29:41
 */
@Service
@SuppressWarnings("unchecked")
public class ResponseService extends EntityService<Response> implements IResponseService {
	@Autowired
	public ResponseService(BaseHibernateDao dao){
		super.setDao(dao);
	}
	
	public void delete(Response response){
		long sum = super.queryForLong("select count(r.id) from Response r where r.parentId = "+response.getId());
		if(sum > 0){
			throw new BackendException("不能删除已有回复的记录");
		}
		getDao().delete(response);
	}
	
	public List<Response> listTree(int responseType, int typeId, boolean audited){
		List<Response> list = getDao().find("from Response r where r.type = ? and r.typeId = ? and r.audited = ? order by r.emitDate asc", responseType, typeId, audited);
		return toTreeStrut(list);
	}
	
	private List<Response> toTreeStrut(List<Response> list){
		Map<Integer, Response> map = new HashMap<Integer ,Response>(list.size());
		
		for(Response res : list){
			map.put(res.getId(), res);
		}
		List<Response> tree = new LinkedList<Response>();
		for(Response res : list){
			Integer parentId = res.getParentId();
			if(parentId != null && parentId > 0){
				Response parent = map.get(parentId);
				if(parent != null){
					List<Response> subs = parent.getSubResponses();
					if(subs == null){
						subs = new LinkedList<Response>();
						parent.setSubResponses(subs);
					}
					subs.add(res);
				}
			}else{
				tree.add(res);
			}
		}
		return tree;
	}
}
